package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.dto.IdentityDTO;
import com.example.entity.IdentityDO;
import com.example.exception.BusinessException;
import com.example.mapper.IdentityMapper;
import com.example.service.IdentityService;
import java.util.Date;
import java.util.List;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *   身份管理服务层实现
 * </p>
 * @author 34448
 */
@Service
public class IdentityServiceImpl implements IdentityService {

    @Autowired
    private IdentityMapper identityMapper;

    @Override
    @Transactional
    public Boolean addIdentity(IdentityDTO identityDTO) {
        QueryWrapper<IdentityDO> wrapper = Wrappers.query();
        wrapper.eq("identity_name", identityDTO.getIdentityName());
        IdentityDO existingIdentity = identityMapper.selectOne(wrapper);
        if (existingIdentity != null) {
            throw new BusinessException("000001", "身份名称已存在");
        }
        IdentityDO identityDO = new IdentityDO();
        BeanUtils.copyProperties(identityDTO, identityDO);
        identityDO.setCreateTime(new Date());
        identityDO.setUpdateTime(new Date());
        return identityMapper.insert(identityDO) > 0;
    }

    @Override
    @Transactional
    public Boolean deleteIdentity(Integer identityId) {
        IdentityDO identityDO = identityMapper.selectById(identityId);
        if (identityDO == null) {
            throw new BusinessException("000001", "身份信息不存在");
        }
        return identityMapper.deleteById(identityId) > 0;
    }

    @Override
    @Transactional
    public Boolean editIdentity(IdentityDTO identityDTO) {
        IdentityDO identityDO = identityMapper.selectById(identityDTO.getIdentityId());
        if (identityDO == null) {
            throw new BusinessException("000001", "身份信息不存在");
        }
        QueryWrapper<IdentityDO> wrapper = Wrappers.query();
        wrapper.eq("identity_name", identityDTO.getIdentityName()).ne("identity_id", identityDTO.getIdentityId());
        IdentityDO existingIdentity = identityMapper.selectOne(wrapper);
        if (existingIdentity != null) {
            throw new BusinessException("000001", "身份名称已存在");
        }
        BeanUtils.copyProperties(identityDTO, identityDO);
        identityDO.setUpdateTime(new Date());
        return identityMapper.updateById(identityDO) > 0;
    }

    @Override
    public List<IdentityDO> queryIdentities(String identityName) {
        QueryWrapper<IdentityDO> wrapper = Wrappers.query();
        if (identityName != null && !identityName.isEmpty()) {
            wrapper.like("identity_name", identityName);
        }
        return identityMapper.selectList(wrapper);
    }
}